package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import com.sun.corba.se.spi.logging.CORBALogDomains;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleLock implements ILock{

    private String name;
    private StringRedisTemplate stringRedisTemplate;


    public SimpleLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String KEY_PERFIX= "lock:";
    private static final String ID_PERFIX= UUID.randomUUID().toString(true);
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static{
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    @Override
    public boolean tryLock(long timeOutSec) {
        //获取线程标识
        String id = ID_PERFIX+Thread.currentThread().getId();
        //获取锁  键值是username相关的,值是线程独一的标号
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PERFIX + name, id , timeOutSec, TimeUnit.SECONDS);

        return Boolean.TRUE.equals(aBoolean);
    }

    @Override
    public void unLock() {

        //调用lua脚本来实现原子性
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PERFIX + name),
                ID_PERFIX+Thread.currentThread().getId()
        );

    }

    /*@Override
    public void unLock() {
        //当前线程的uuid
        String id = ID_PERFIX+Thread.currentThread().getId();
        //从redis中获取
        String s = stringRedisTemplate.opsForValue().get(KEY_PERFIX + name);
        //判断标号是否一致
        if(id.equals(s)){
            //释放锁
            stringRedisTemplate.delete(KEY_PERFIX + name);
        }

    }*/
}
